<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
        <el-button type="primary" @click="addRoleDialog()">添加角色</el-button>

        <el-table :data="rolesList" border stripe>
            <el-table-column
                type="expand"
            >
            <!-- 下拉权限视图 -->
            <template v-slot='scope'>
                <el-row :class="['bd-bottom' ,'vcenter',itemIndex === 0 ? 'bd-top' : '']" v-for="(item,itemIndex) in scope.row.children" :key="item.id">
                    <!-- 一级权限 -->
                    <el-col :span="5">
                        <el-tag
                        closable
                        :disable-transitions="false"
                        @close="handleClose(scope.row,item.id)">
                        {{item.authName}}
                        </el-tag>
                        <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 二级权限 -->
                    <el-col :span="19">
                        <!-- 通过for循环嵌套渲染二级权限 -->
                        <el-row :class="['vcenter',itemChildIndex === 0 ? '':'bd-top']" v-for="(itemChild,itemChildIndex) in item.children" :key='itemChild.id'>
                            <el-col :span="5">
                                <el-tag
                                    closable
                                    :disable-transitions="false"
                                    @close="handleClose(scope.row,itemChild.id)"
                                    type="success"
                                >
                                {{itemChild.authName}}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 三级权限 -->
                            <el-col :span="19">
                                    <el-tag
                                        closable
                                        :disable-transitions="false"
                                        @close="handleClose(scope.row,itemChildChild.id)"
                                        type="warning"
                                        v-for="itemChildChild in itemChild.children" :key="itemChildChild.id"
                                    >
                                    {{itemChildChild.authName}}
                                    </el-tag>
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
            </template>
            </el-table-column>
            <el-table-column
                type="index"
                label='#'
            >
            </el-table-column>
            <el-table-column
                prop="roleName"
                label='角色名称'
            >
            </el-table-column>
            <el-table-column
                prop="roleDesc"
                label='角色描述'
            >
            </el-table-column>
            <el-table-column
                label='操作'
                width="290"
            >
            <template v-slot='scope'>
                <el-tooltip content="编辑角色" placement="top" :enterable='false'>
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
                </el-tooltip>
                <el-tooltip content="删除角色" placement="top" :enterable='false'>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="delRole(scope.row.id)">删除</el-button>
                </el-tooltip>
                <el-tooltip content="分配给角色权限" placement="top" :enterable='false'>
                <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                </el-tooltip>
            </template>
            </el-table-column>
        </el-table>
        <!-- 添加角色表单对话框 -->
        <el-dialog
            title="添加角色"
            :visible.sync="addRoleDialogVisible"
            @close = 'addDialogClosed'
        >
            <el-form
                :model="addForm"
                :rules="addFormRules"
                ref='addFormRef'
            >
                <el-form-item 
                    label="角色名称"
                    prop='roleName'
                >
                    <el-input v-model="addForm.roleName">
                    </el-input>
                </el-form-item>
                <el-form-item 
                    label="角色描述"
                    prop='roleDesc'
                >
                    <el-input v-model="addForm.roleDesc">
                    </el-input>
                </el-form-item>
                <!-- 底部区域 -->
                <el-button @click="addRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary"  @click="addRole">确 定</el-button>
            </el-form>

        </el-dialog>

        <!-- 修改角色对话框 -->
      <el-dialog
        title="修改角色"
        :visible.sync="editRoleDialogVisible"
        width="50%" @close='editDialogClosed'
      >
        <!-- 内容主体区域 -->
        <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="80px">
          <el-form-item label="ID" prop="roleId">
          <el-input v-model="editForm.roleId" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary"  @click="editRole">确 定</el-button>
      </el-dialog>

        <!-- 修改角色权限对话框 -->
      <el-dialog
        title="修改角色权限"
        :visible.sync="setRightDialogVisible"
        width="50%"
        @close='setRightDialogClose'
      >
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defalutCheckedID"
      ref="trees"
      ></el-tree>
        <!-- 底部区域 -->
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRight">确 定</el-button>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
    name:'Roles',
    data(){
        return {
            rolesList:[],
            // 接收到的权限参数
            rightsList:[],
            // 显示或隐藏添加角色对话框
            addRoleDialogVisible:false,
            // 显示或隐藏编辑角色对话框
            editRoleDialogVisible:false,
            // 显示或隐藏修改角色权限对话框
            setRightDialogVisible:false,
            // 添加角色的表单数据
            addForm:{
                roleName:'',
                roleDesc:''
            },
            // 查询到的角色信息对象
            editForm:{

            },
            // 当前正在赋予权限的角色ID
            roleId:'',
            // 添加表单验证规则对象,与表单中的prop对应
            addFormRules:{
                roleName:[
                     { required: true, message: '请输入角色名称', trigger: 'blur' },   
                ],
                roleDesc:[
                     { required: true, message: '请输入角色描述', trigger: 'blur' },    
                ]
            },
            // 树形控件的属性绑定对象
            treeProps:{
               children: 'children',
                label: 'authName' 
            },
            // 默认选中的权限ID
            defalutCheckedID:[]
        }
    },
    methods:{
       async getRolesList(){
            const {data: res} = await this.$http.get('roles')
            if(res.meta.status !== 200){
                return this.$message.console.error('获取角色列表失败');
            }
            this.rolesList = res.data
        },
        // 显示添加角色对话框
        addRoleDialog(){
            this.addRoleDialogVisible = true
        },
        addRole(){
            this.$refs.addFormRef.validate(async valid =>{
                if(! valid) return 
                const {data: res} = await this.$http.post('roles',{roleName:this.addForm.roleName,roleDesc:this.addForm.roleDesc})
                if(res.meta.status !== 201){
                    return this.$message.error('添加角色失败')
                }
                this.$message.success('添加角色成功！')
                this.addRoleDialogVisible = false
                this.getRolesList()
            })
        },
        // 表单关闭时
        addDialogClosed(){
                  // resetFields()对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
            this.$refs.addFormRef.resetFields()
        },
        // 编辑角色按钮
        async showEditDialog(id){
            this.editRoleDialogVisible = true;
            const {data: res} = await this.$http.get(`roles/${id}`)
            if(res.meta.status !== 200) {
                this.$message.error('获取角色信息失败')
            }
            this.editForm = res.data
        },
        // 编辑角色信息并发送
        editRole(){
            this.$refs.editFormRef.validate(async valid =>{
                if(!valid) return
                const{data: res} = await this.$http.put(`roles/${this.editForm.roleId}`,{roleName:this.editForm.roleName,roleDesc:this.editForm.roleDesc})
                console.log(res)
                if(res.meta.status !== 200){
                    return this.$message.error('编辑角色失败')
                }
                this.$message.success('编辑角色成功')
                this.editRoleDialogVisible = false
                this.getRolesList()
            })
        },
        // 当编辑角色对话框关闭时清除对话框内容
        editDialogClosed(){
            this.$refs.editFormRef.resetFields();
        },
        // 删除角色
        async delRole(id){
            const confirmResult = await this.$confirm('此操作将删除该用户，是否确定','提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          }).catch(err => err)
          if(confirmResult !== 'confirm'){
              return this.$message.error('取消删除')
          }
          const {data: res} = await this.$http.delete(`roles/${id}`)
          if(res.meta.status !== 200){
              return this.$message.error('删除角色失败')
          }
          this.$message.success('删除角色成功')
          this.getRolesList()
        },
        // 删除角色权限
       async handleClose(role,rightId){
        const confirmResult = await this.$confirm('此操作将删除该权限，是否确定','提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          }).catch(err => err)
          if(confirmResult !== 'confirm'){
              return this.$message.error('取消删除')
          }
          const {data: res} = await this.$http.delete(`roles/${role}/rights/${rightId}`)
          if(res.meta.status !== 200){
              return this.$message.error('删除权限失败')
          }
          this.$message.success('删除权限成功')
        //   防止整个列表刷新
          role.children = res.data
        //   this.getRolesList()
    },
    // 展示修改角色权限对话框
    async showSetRightDialog(role){
        // 在展示修改角色权限对话框之前，先将正在修改权限的角色ID给到data中，这样在下一步对角色权限进行分配时，可以直接拿到角色ID
       this.roleId = role.id
        // 获取所有权限设置
        const{data: res} = await this.$http.get('rights/tree')
        if(res.meta.status !==200){
            return this.$message.err('获取权限数据失败')
        }
        // 把获取到的权限数据保存到data中 
        this.rightsList = res.data
        // console.log(this.rightsList)
        // 递归获取所有三级节点的id
        this.getLeafKeys(role,this.defalutCheckedID)
        this.setRightDialogVisible = true
    } ,
    // 点击为角色分配权限
    async setRight(){
        const keys = [
        ...this.$refs.trees.getCheckedKeys(),
        ...this.$refs.trees.getHalfCheckedKeys(),
        ]
        // console.log(keys)
        const idStr = keys.join(',')
        console.log(idStr,typeof idStr)
        const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
        if(res.meta.status !== 200) {
            return this.$message.error('修改角色权限失败')
        }
        this.$message.success('分配角色权限成功')
        this.getRolesList()
        this.setRightDialogVisible = false
    },
    // 通过递归形式，获取所有三级权限的id，并保存到数组中
    getLeafKeys(node,arr){
        // 如果当前节点不包含children，则是三级节点
        if(!node.children){
            return arr.push(node.id)
        }
        // forEach() 方法对数组的每个元素执行一次给定的函数
        node.children.forEach(item =>{
            this.getLeafKeys(item,arr)
        })
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClose(){
        this.defalutCheckedID = []
    }
},
    created(){
        this.getRolesList()
    }
}
</script>

<style>
.el-tag {
    margin: 10px;
}
.bd-top {
    border-top: 1px solid #eee;
}
.bd-bottom {
border-bottom: 1px solid #eee; 
}
</style>